package com.example.demo.service.impl;

import com.example.demo.dao.SearchResponse;
import com.example.demo.dao.User;
import com.example.demo.dao.UserExample;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //分页查询员工
    @Override
    public SearchResponse listUser(Integer pageNum, Integer pageSize, String keyword) {
        keyword = "%" + keyword + "%";
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();
        example.or().andUsernameLike(keyword);
        List<User> users = userMapper.selectByExample(example);
        return new SearchResponse(((Page) users).getTotal(), users);
    }

    //删除一行
    @Override
    public int deleteUserByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    //批量删除

    @Override
    public int multiDelUsers(String ids) {
        UserExample example = new UserExample();
        List<String> list = Arrays.asList(ids.split(","));
        List<Integer> ilist = list.stream().map(Integer::parseInt).collect(Collectors.toList());
        example.or().andUseridIn(ilist);
        return userMapper.deleteByExample(example);
    }

    //得到选中用户的信息
    @Override
    public User findUserByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    //保存编辑后的用户信息
    @Override
    public int editUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }


    //用户登录
    @Override
    public User login(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return userMapper.login(user);
    }

    @Override
    public int zhuce(User user) {
        return userMapper.insert(user);
    }

    //个人信息
    @Override
    public User findUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User findUserByEmail(String email) {
        UserExample userExample  = new UserExample();
        UserExample.Criteria criteria= userExample.createCriteria();
        criteria.andEmailEqualTo(email);
        return userMapper.selectByExample(userExample).get(0);
    }


}